package com.joysuch.wwyt.config;

import lombok.extern.slf4j.Slf4j;
import org.influxdb.InfluxDB;
import org.influxdb.InfluxDBFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

/**
 * @author qingzhou
 * 2019-11-20
 */
@Slf4j
@Configuration
@PropertySource(value = "classpath:influxdb.properties", encoding = "UTF-8")
public class InfluxDBConfig {

    @Value("${influxdb.url}")
    private String url;
    @Value("${influxdb.username}")
    private String username;
    @Value("${influxdb.password}")
    private String password;
    @Value("${influxdb.database}")
    private String database;
    @Value("${influxdb.retention.policy}")
    private String retentionPolicy;

    @Bean
    public InfluxDB initDB() {
        InfluxDB influxDB = InfluxDBFactory.connect(url, username, password);
        try {
            influxDB.setDatabase(database);
        } catch (Exception e) {
            log.error("create influx db failed, error: {}", e.getMessage());
            throw new RuntimeException("init influx db failed.", e);
        } finally {
            influxDB.setRetentionPolicy(retentionPolicy);
        }
        influxDB.setLogLevel(InfluxDB.LogLevel.BASIC);
        return influxDB;
    }

}
